import { DependencyContainer } from "tsyringe";
import multer, { Options } from 'multer'
import { ROOT, Request, Response } from "@sker/core";
import { join } from "path";
import { Readable } from "stream";
export interface File {
    fieldname: string;
    originalname: string;
    encoding: string;
    mimetype: string;
    size: number;
    stream: Readable;
    destination: string;
    filename: string;
    path: string;
    buffer: Buffer;
}
export interface MulterHandler {
    (m: File): Promise<any>
}
export const useMulter = async (injector: DependencyContainer, handler: MulterHandler, name: string = 'file', options: Options = {}) => {
    const root = injector.resolve(ROOT)
    const req = injector.resolve(Request)
    const res = injector.resolve(Response)
    const upload = multer({ dest: join(root, 'attachments'), ...options })
    return new Promise((resolve, reject) => {
        upload.single(name)(req, res, async (err) => {
            if (err) return reject(err)
            try {
                const result = await handler(req.file)
                resolve(result)
            } catch (e) {
                return reject(err)
            }
        })
    })
}

export default useMulter;
